package com.zj.zhao.reflection;

import com.zj.zhao.reflection.bean.UserController;
import com.zj.zhao.reflection.bean.UserService;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionDemo {

    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        UserController userController = new UserController();
        UserService userService = new UserService();

        // 完成注入的功能
        Class<? extends UserController> clazz = userController.getClass();
        // 获取属性
        Field serviceField = clazz.getDeclaredField("userService");
        // 设置访问属性
//        serviceField.setAccessible(true);
        // 获取对应的 set 方法
        String name = serviceField.getName();
        name = name.substring(0, 1).toUpperCase() + name.substring(1); // UserService

        String methodName = "set" + name;
        Method method = clazz.getMethod(methodName, UserService.class);
        // 调用 setUserService 方法
        method.invoke(userController, userService);
        System.out.println(userController);

        // 直接设置属性 anotherUserService
        Field anotherUserServiceField = clazz.getDeclaredField("anotherUserService");
        anotherUserServiceField.setAccessible(true);
        anotherUserServiceField.set(userController, userService);
        System.out.println(userController);
    }
}
